package com.mrzhou.gateway.filter;

import com.mrzhou.gateway.provider.RequestProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.RequestPredicate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * 打印webflux的日志
 *
 *  <p>
 *   注意：暂时不支持结构体打印，想实现，请看下面的链接。
 *   https://stackoverflow.com/questions/45240005/how-to-log-request-and-response-bodies-in-spring-webflux
 *   https://github.com/Silvmike/webflux-demo/blob/master/tests/src/test/java/ru/hardcoders/demo/webflux/web_handler/filters/logging
 *  </p>
 *
 */
@Slf4j
@Component
public class GlobalRequestLogFilter implements GlobalFilter, Ordered {

    private final WebEndpointProperties endpointProperties;

    public GlobalRequestLogFilter(WebEndpointProperties endpointProperties) {
        this.endpointProperties = endpointProperties;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求的路径
        String path = request.getPath().pathWithinApplication().value();

        // 忽略 endpoint 请求
        String endpointBasePath =endpointProperties.getBasePath();
        if(StringUtils.isNotBlank(endpointBasePath) && path.endsWith(endpointBasePath)) {
            return chain.filter(exchange);
        }

        String requestUrl = RequestProvider.getOriginRequestUrl(exchange);

        StringBuilder sb = new StringBuilder(500);
        List<Object> beforeReqArgs = new ArrayList<>();
        sb.append("\n\n================ Gateway Request Start  ================\n");
        // 打印路由
        sb.append("===> {}: {}\n");
        beforeReqArgs.add(request.getMethodValue());
        beforeReqArgs.add(requestUrl);

        // 打印请求头
        HttpHeaders headers = request.getHeaders();
        headers.forEach((key, value) -> {
            sb.append("===Headers===  {}: {}\n");
            beforeReqArgs.add(key);
            beforeReqArgs.add(value);
            beforeReqArgs.add(StringUtils.join(value));
        });
        sb.append("================  Gateway Request End  =================\n");

        // 打印执行时间
        log.info(sb.toString(), beforeReqArgs.toArray());

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
